#!/bin/bash
TMPFILE="/tmp/clean_all_quota_tmpfile"
OP=$1
source ${QUOTA_COMMON_FUNC}

function print_help() {
    name="$0"
    echo "Usage:"
    echo "  sh ${name}        帮助信息"
    echo "  sh ${name} 0      打印执行的命令, 但是不执行真正的清理"
    echo "  sh ${name} 1      打印执行的命令, 并执行真正的清理"
}

function clean_wholedir_quota() {
    quota_num=`orcafs-ctl --listquota | grep -w DIR | wc -l`
    if ((${quota_num} == 0));then return; fi;

    for dir in `orcafs-ctl --listquota | grep -w DIR | awk '{print $10}'`
    do
        echo -e "\t orcafs-ctl --removequota --dir=${dir}"
        if ((${OP} == 1));then
            eval orcafs-ctl --removequota --dir=${dir} #&> /dev/null
        fi
    done
}

function clean_uiddir_quota() {
    quota_num=`orcafs-ctl --listquota | grep -w DIR_UID | wc -l`
    if ((${quota_num} == 0));then return; fi;

    orcafs-ctl --listquota | grep -w DIR_UID | awk '{print $11 " " $3}' > ${TMPFILE}
    while read dir uid
    do
        echo -e "\t orcafs-ctl --removequota --dir=${dir} --uid=${uid}"
        if ((${OP} == 1));then
            eval orcafs-ctl --removequota --dir=${dir} --uid=${uid} #&> /dev/null
        fi
    done < ${TMPFILE}
    rm -f ${TMPFILE}
}

function clean_giddir_quota() {
    quota_num=`orcafs-ctl --listquota | grep -w DIR_GID | wc -l`
    if ((${quota_num} == 0));then return; fi;

    orcafs-ctl --listquota | grep -w DIR_GID | awk '{print $11 " " $3}' > ${TMPFILE}
    while read dir gid
    do
        echo -e "\t orcafs-ctl --removequota --dir=${dir} --gid=${gid}"
        if ((${OP} == 1));then
            eval orcafs-ctl --removequota --dir=${dir} --gid=${gid} #&> /dev/null
        fi
    done < ${TMPFILE}
    rm -f ${TMPFILE}
}

if [ "$1" == "--help" ] || [ -z "$1" ];then print_help; exit; fi

quota_num=`orcafs-ctl --listquota | grep DIR | wc -l`
if ((${quota_num} == 0));then echo -e "=====清理配额信息(null)===== success"; exit 0; fi

echo "=====清理所有配额之前====="
orcafs-ctl --listquota | grep DIR
echo "=====执行清理====="
clean_wholedir_quota;
clean_uiddir_quota;
clean_giddir_quota;

if ((${OP} == 1));then
    quota_num=`orcafs-ctl --listquota | grep DIR | wc -l`
    if ((${quota_num} == 0));then 
        echo -e "=====清理配额信息===== success"; sleep ${WAIT_CLIENT_SYNC}; exit 0; 
    else
        echo -e "=====清理配额信息===== fail"; exit 0;
    fi
fi
